dojo.provide("miaigo.model.MoveReference");

dojo.declare(
    "miaigo.model.MoveReference",
    null,
    {
	// [ {tree: Number, move: Number}, ...]
	_path: null,
	_model: null,

	constructor: function(/* miaigo.model.Game */game)
	{
	    this._model = game;

	    if (game && game.getTrunk)
	    {
		// start from the first tree and no move
		this.fromString("0:-1");
	    }
	},

	fromString: function(/* String */refString)
	{
	    this._path = [];

	    var parts = refString.split("/");
	    for (var i in parts)
	    {
		var pair = parts[i].split(":");
		if (pair && pair.length == 2)
		{
		    var treeID = parseInt(pair[0]);
		    var moveID = parseInt(pair[1]);

		    if (!isNaN(treeID) && !isNaN(moveID))
		    {
			this._path.push( { tree: treeID, move: moveID } );
		    }
		}
	    }
	},

	toString: function()
	{
	    var result = "";
	    for (var i in this._path)
	    {
		result += "/" + this._path[i].tree + ":" + this._path[i].move;
	    }
	    return result;
	},

	// return: miaigo.model.Move
	getMove: function()
	{
	    if (!this._path || this._path.length <= 0)
	    {
		return null;
	    }

	    var trunk = this._model.getTrunk();
	    if (this._path[0].tree == 0 && trunk)
	    {
		var move = this._getMoveFromTree(trunk, this._path[0].move);

		for (var i=1; i<this._path.length; i++)
		{
		    var tree = move.getAlternation(this._path[i].tree);
		    move = this._getMoveFromTree(tree, this._path[i].move);
		}

		return move;
	    }

	    return null;
	},

	_getMoveFromTree: function(/* MoveTree */tree, /* Number */moveIndex)
	{
	    if (moveIndex >= 0)
	    {
		return tree.getMove(moveIndex);
	    }
	    else
	    {
		var move = tree.getOwner();
		if (move)
		{
		    return move;
		}
		else
		{
		    // an empty move
		    return new miaigo.model.Move();
		}
	    }
	},

	next: function()
	{
	    if (this._path && this._path.length > 0)
	    {
		var last = this._path.length - 1;
		this._path[last].move++;
	    }
	},

	prev: function()
	{
	    if (this._path && this._path.length > 0)
	    {
		var last = this._path.length - 1;
		if (this._path[last].move >= 0)
		{
		    this._path[last].move--;
		}
	    }
	}
    });